﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using bestsearch.Resources;
using bestsearch.ViewModels;
using bestsearch.ServiceReference1;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Phone.Tasks;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Input;

namespace bestsearch
{
    public partial class MainPage : PhoneApplicationPage
    {
        private object o = new object();
        public bool IsLoading = false;
        private static List<prt> lprt =new List<prt>();
         private static int nowcount =0;
        private static string q = "vip";
         private static ServiceReference1.WebService1SoapClient ts = new WebService1SoapClient();
        // 构造函数
         private static bool newstart= true;
        public MainPage()
        {
            InitializeComponent();
            ts.getletvCompleted += ts_getletvCompleted;
          
            // 将 LongListSelector 控件的数据上下文设置为示例数据
            // DataContext = App.ViewModel;

            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();
        }

        // 为 ViewModel 项加载数据
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        // 处理在 LongListSelector 中更改的选定内容
        private void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 如果所选项为空(没有选定内容)，则不执行任何操作
            if (MainLongListSelector.SelectedItem == null)
                return;

            // 导航到新页面
            //  NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + (MainLongListSelector.SelectedItem as prt).id, UriKind.Relative));
            string selectedIndex = (MainLongListSelector.SelectedItem as prt).id;
            string fromurl = HttpUtility.UrlEncode(selectedIndex.ToString());
            WebRequest http = WebRequest.Create("http://www.flvcd.com/parse.php?format=&kw=" + selectedIndex);
            // http.Referer = oauth;
            //  http.Method = "GET";
            //  http.ContentType = "application/x-www-form-urlencoded";
            // http.AllowAutoRedirect = true;
            //  http.KeepAlive = true;
            //  http.CookieContainer = MyCookieContainer;
            object rf = new object();
            http.BeginGetResponse((r) =>
            {

                WebResponse resp = (WebResponse) http.EndGetResponse(r);
                //  HttpWebResponse httpRequest = (HttpWebResponse) httpRequest.EndGetResponse(r);
                using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
                {
                    string org = reader.ReadToEnd().ToString();
                    // richTextBox1.Text = org;
                    // reader.Close();
                    //  response.Close();
                    resp.Close();

                    string rs = "<a href=\"([^\"]+)\" target=\"_blank\" class=\"link\" ";
                    var match = Regex.Match(org, rs);
                    string rich = match.Groups[1].Value;
                    //  Deployment.Current.Dispatcher.BeginInvoke(new Action(() => { wb.Navigate(new Uri(rich)); }));
                    Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MediaPlayerLauncher mpl = new MediaPlayerLauncher();
                        mpl.Location = MediaLocationType.Install;

                        //设置所有控制纽都出现

                        mpl.Controls = MediaPlaybackControls.All;

                        //设置出现停止按钮以及暂停按钮

                        mpl.Controls = MediaPlaybackControls.Pause | MediaPlaybackControls.Stop;

                        //设置播放的文件

                        //  mpl.Media = new Uri("http://g3.letv.cn/vod/v2/NjkvMjUvMTQvbGV0di11dHMvMTQvdmVyXzAwXzE0LTIxMzU2Njc1LWF2Yy0zMjIwNjEtYWFjLTEyODAwNi02Nzk2OC0zOTM2MTAwLWU4YWIxYmE4MGE4MmE3MjE4MzQxNGVlM2RlZGMwMzU1LTE0MDE2Njk4NzI0OTcubXA0?b=462&mmsid=20926978&tm=1402019122&key=6958fb4f7e1c083d0d82e0bc16485c94&platid=1&splatid=101&playid=0&tss=0&vtype=21&cvid=311354022041&termid=1&format=0&hwtype=un&ostype=Windows7&tag=letv&sign=letv&expect=1&pay=0&rateid=350", UriKind.RelativeOrAbsolute);
                        mpl.Media = new Uri(rich, UriKind.RelativeOrAbsolute);
                        //启动播放

                        mpl.Show();


                    }));
                }
            }
                , null);
            // int index = int.Parse(selectedIndex);

            // 将所选项重置为 null (没有选定内容)
            MainLongListSelector.SelectedItem = null;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
          
            /* ts.HelloWorldCompleted += ts_HelloWorldCompleted;
            ts.HelloWorldAsync();*/
            newstart = true;
            ts.getletvAsync(q, nowcount.ToString());
        }
        public static bool IsChinese(string CString)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(CString, @"[\u4e00-\u9fa5]");
            // return Regex.IsMatch(CString, @"^[\u4e00-\u9fa5]+$");
        }

        private void ts_getletvCompleted(object sender, getletvCompletedEventArgs e)
        {
            if (newstart)
            {

                 lprt=new List<prt>();
                //  throw new NotImplementedException();
                StringReader sr = new StringReader(e.Result.ToString());
                XmlSerializer xr = new XmlSerializer(typeof (fx<prt>));
                fx<prt> f = xr.Deserialize(sr) as fx<prt>;
                foreach (prt y in f.shuju)
                {
                    y.content = IsChinese(q)
                        ? (y.content.ToString().IndexOf(q) != -1
                            ? (y.content.ToString().Substring(y.content.ToString().IndexOf(q)).Length > 200
                                ? y.content.ToString().Substring(y.content.ToString().IndexOf(q)).Substring(0, 200)
                                : y.content.ToString().Substring(y.content.ToString().IndexOf(q)))
                            : (y.content.ToString().Length > 200
                                ? y.content.ToString().Substring(0, 200)
                                : y.content.ToString()))
                        : (y.content.ToString().Substring(y.content.ToString().ToLower().IndexOf(q.ToLower())).Length >
                           200
                            ? y.content.ToString()
                                .Substring(y.content.ToString().ToLower().IndexOf(q.ToLower()))
                                .Substring(0, 200)
                            : y.content.ToString()
                                .ToLower()
                                .Substring(y.content.ToString().ToLower().IndexOf(q.ToLower())));
                }
                // MessageBox.Show(f.numcount.ToString());
                lprt.AddRange(f.shuju.ToList());
                nowcount += 20;

                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    MainLongListSelector.DataContext = lprt.ToList();
                    MainLongListSelector.ScrollTo(lprt[lprt.Count - 20]);
                }));
            }
            else
            {
                StringReader sr = new StringReader(e.Result.ToString());
                XmlSerializer xr = new XmlSerializer(typeof(fx<prt>));
                fx<prt> f = xr.Deserialize(sr) as fx<prt>;
                foreach (prt y in f.shuju)
                {
                    y.content = IsChinese(q)
                        ? (y.content.ToString().IndexOf(q) != -1
                            ? (y.content.ToString().Substring(y.content.ToString().IndexOf(q)).Length > 200
                                ? y.content.ToString().Substring(y.content.ToString().IndexOf(q)).Substring(0, 200)
                                : y.content.ToString().Substring(y.content.ToString().IndexOf(q)))
                            : (y.content.ToString().Length > 200
                                ? y.content.ToString().Substring(0, 200)
                                : y.content.ToString()))
                        : (y.content.ToString().Substring(y.content.ToString().ToLower().IndexOf(q.ToLower())).Length >
                           200
                            ? y.content.ToString()
                                .Substring(y.content.ToString().ToLower().IndexOf(q.ToLower()))
                                .Substring(0, 200)
                            : y.content.ToString()
                                .ToLower()
                                .Substring(y.content.ToString().ToLower().IndexOf(q.ToLower())));
                }
                // MessageBox.Show(f.numcount.ToString());
                lprt.AddRange(f.shuju.ToList());
                nowcount += 20;

                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    MainLongListSelector.DataContext = lprt.ToList();
                    MainLongListSelector.ScrollTo(lprt[lprt.Count - 20]);
                }));
            }
        }

        private void ts_HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs e)
        {
            //  throw new NotImplementedException();

            StringReader sr = new StringReader(e.Result.ToString());
            XmlSerializer xr = new XmlSerializer(typeof (fx<prt>));
            fx<prt> f = xr.Deserialize(sr) as fx<prt>;
            // MessageBox.Show(f.numcount.ToString());
            MainLongListSelector.DataContext = f.shuju.ToList();
        }

        private void MainLongListSelector_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            lock (o)

            {

                if (!IsLoading)

                {

                    if (e.ItemKind == LongListSelectorItemKind.Item)

                    {
                        newstart = false;
                        if ((e.Container.Content as prt).Equals(MainLongListSelector.ItemsSource[MainLongListSelector.ItemsSource.Count - 1]))
                        {
                             IsLoading = true;

                            // 显示体系托盘的进度条

                            Microsoft.Phone.Shell.ProgressIndicator progressIndicator = new Microsoft.Phone.Shell.ProgressIndicator();

                            Microsoft.Phone.Shell.SystemTray.ProgressIndicator = progressIndicator;

                            progressIndicator.Text = "加载中...";

                            progressIndicator.IsIndeterminate = true;

                            progressIndicator.IsVisible = true;

                            // 模仿后台耗时任务拉取数据的场景

                            Task.Factory.StartNew(async () =>

                            {

                                await Task.Delay (3000);

                                // 调用UI线程添加数据

                                this.Dispatcher.BeginInvoke (new Action(() =>

                                {

                                    /*int count = Items.Count;

                                    for (int i = count; i < count + 50; i++)

                                    {

                                        Items.Add(new Item { FirstName = "Li" + i， LastName = "Lei" + i });

                                    }*/
                                  //  ts.getletvCompleted += ts_getletvCompleted;
                                    ts.getletvAsync(q, nowcount.ToString());
                                    // 封闭进度条

                                    progressIndicator.IsVisible = false;

                                    // 批改加载的状况

                                    IsLoading = false;

                                }));

                            });
                        }
                    }
                }
            }

            // 用于生成本地化 ApplicationBar 的示例代码
            //private void BuildLocalizedApplicationBar()
            //{
            //    // 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
            //    ApplicationBar = new ApplicationBar();

            //    // 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
            //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
            //    appBarButton.Text = AppResources.AppBarButtonText;
            //    ApplicationBar.Buttons.Add(appBarButton);

            //    // 使用 AppResources 中的本地化字符串创建新菜单项。
            //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
            //    ApplicationBar.MenuItems.Add(appBarMenuItem);
            //}
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (tba.Text != "请输入关键字")
            {
                q = tba.Text.Trim().ToString();
            }
        }

        private void tba_GotFocus(object sender, RoutedEventArgs e)
        {
            tba.Text = "";
        }

        private void tba_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.Focus();
                newstart = true;
                
                ts.getletvAsync(q, nowcount.ToString());
            }
        }
    }
}